import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/a_yyt/models/policy_warning_entity.dart';
import 'package:ls_work/a_yyt/page/policy_deal_page.dart';
import 'package:ls_work/a_yyt/page/policy_record_page.dart';
import 'package:ls_work/a_yyt/widget/policy_cell.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/util/event_bus.dart' as e;
import 'package:oktoast/oktoast.dart';

bool isInWarning = false;
class PolicyReminePage extends StatefulWidget {

  @override
  _PolicyReminePageState createState() => _PolicyReminePageState();
}

class _PolicyReminePageState extends State<PolicyReminePage> {
  EasyRefreshController _controller = EasyRefreshController();
  List<PendingSelectedGroupEntity> chipDateList = [];
  List<PolicyWarningInfo> dataList = [];
  List<PolicyWarningInfo> chooseList = [];
  
  var inBatchMode = false;

  int cellType = 0;
  int _page = 1;
  List<Color> titleColors = [
    Colors.red,
    Colors.green[300]!,
    Colors.blue,
  ];
  @override
  void initState() {
    super.initState();
    if(!mounted){
      return;
    }
    isInWarning = true;
    chipDateList = [
      PendingSelectedGroupEntity(
          isSelected: true, id: 0, name: '待处理', count: 0),
      PendingSelectedGroupEntity(
          isSelected: false, id: 1, name: '处理中', count: 0),
      PendingSelectedGroupEntity(
          isSelected: false, id: 2, name: '今日已处理', count: 0),
    ];
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectTopItemCount();
      _fectData();
    });

    e.eventBus.on("warning", (arg) {
      if(mounted){
        _fectTopItemCount();
        _fectData();
      }
    });
  }

  @override
  void dispose() {
    e.eventBus.off("warning");
    isInWarning = false;
    print("退出");
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text('报警处理'),
        actions: [
          if(GlobalConfigs.batchDealWarning)
          (CommonText( inBatchMode?'取消':'批量处理').onTap((){
            setState(() {
              inBatchMode = !inBatchMode;
              chooseList.clear();
            });
          })).addToContainer(
            alignment: Alignment.center,
            margin: EdgeInsets.symmetric(horizontal: 16)
          )
        ],
        elevation: 0.5,
      ),
      body: Container(
        height: ScreenUtil.getScreenH(context),
        width: ScreenUtil.getScreenW(context),
        padding: EdgeInsets.fromLTRB(15, 15, 15, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: chipDateList.map((e) {
                int index = chipDateList.indexOf(e);
                print(e.count);
                return GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    if (index == 2) {
                      AppNavigator.push(context, PolicyRecordPage());
                      return;
                    }
                    if (e.isSelected == true) return;
                    setState(() {
                      for (var item in chipDateList) {
                        if (item.id == e.id) {
                          cellType = item.id??0;
                          e.isSelected = true;
                          _onRefresh();
                        } else {
                          item.isSelected = false;
                        }
                      }
                    });
                  },
                  child: Container(
                    width: (ScreenUtil.getScreenW(context) - 50) / 3,
                    decoration: BoxDecoration(
                      color: e.isSelected==true ? Colors.orange[50] : Colors.white,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: e.isSelected==true ? Colors.orange[100]! : Colors.white,
                      ),
                    ),
                    padding: EdgeInsets.fromLTRB(0, 15, 0, 15),
                    child: Column(
                      children: [
                        Text(
                          '${e.count}',
                          style: TextStyle(
                            color: titleColors[index],
                            fontSize: 22,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Gaps.vGap10,
                        Text(
                          '${e.name}',
                          style: TextStyle(
                            color: Colours.text_gray,
                            fontSize: 18,
                          ),
                        ),
                      ],
                    ),
                  ),
                ).setWeight(1);
              }).toList().insertWidget(SizedBox(width: 10,)),
            ),
            Expanded(
              child: EasyRefresh(
                onRefresh: _onRefresh,
                onLoad: _loadMore,
                header: MaterialHeader(),
                footer: MaterialFooter(),
                enableControlFinishLoad: true,
                controller: _controller,
                emptyWidget: dataList.length > 0 ? null : Gaps.emptyContainer,
                child: ListView.builder(
                  itemCount: dataList.length,
                  itemBuilder: (_, int index) {
                    return InkWell(
                      onTap: () {
                        if(!inBatchMode){
                          AppNavigator.push(
                            context,
                            PolicyDealPage(
                              info: dataList[index],
                              callBack: _onRefresh,
                            ),
                          );
                        }else{
                          setState(() {
                            if(chooseList.contains(dataList[index])){
                              chooseList.remove(dataList[index]);
                            }else{
                              chooseList.add(dataList[index]);
                            }
                          });
                        }
                      },
                      child: PolicyCell(
                        type: cellType,
                        info: dataList[index],
                        inBatchMode: inBatchMode,
                        isChoose: chooseList.contains(dataList[index]),
                        callBack: () {
                          _warninghCallBack(dataList[index].id!);
                        },
                      ),
                    );
                  },
                ),
              ),
            ),
            if(inBatchMode)
             ...[
               Row(
                 children: [
                   TextButton(onPressed: (){
                     setState(() {
                       if(dataList.length==chooseList.length){
                         chooseList.clear();
                       }else{
                         chooseList.clear();
                         chooseList.addAll(dataList);
                       }
                     });
                   }, child: CommonText(dataList.length==chooseList.length? '取消全选':'全选',textColor: Colors.white),
                     style: TextButton.styleFrom(
                         backgroundColor: Colors.orange,
                         shape: RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(left: 30.radius))
                     ),).setWeight(1),


                   TextButton(onPressed: (){
                     batchSubmit();
                   }, child: CommonText('批量提交',textColor: Colors.white),
                     style: TextButton.styleFrom(
                         backgroundColor: Colors.blue,
                         shape: RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(right: 30.radius))
                     ),).setWeight(1),
                 ],
               ),
               SizedBox(height: 20,)
             ]
          ],
        ),
      ),
    );
  }

  _fectTopItemCount() async {
    var map = {
      'dataStatisticsDateStart':
          DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
      'dataStatisticsDateEnd':
          DateUtil.formatDate(DateTime.now(), format: DateFormats.full),
      "needTime":"1"
      // "dataStatisticsDateStart": "2020-07-16 00:00:00",
      // "dataStatisticsDateEnd": "2020-07-16 23:00:00",
    };
    HttpUtil.instance
        .getDio()
        .post(HttpApi.policyWarningCount, data: map)
        .then((r) {
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          setState(() {
            if (map['data']['waitDealSum'] != null) {
              chipDateList[0].count = map['data']['waitDealSum'];
            }
            if (map['data']['dealingSum'] != null) {
              chipDateList[1].count = map['data']['dealingSum'];
            }
            if (map['data']['dealedSum'] != null) {
              chipDateList[2].count = map['data']['dealedSum'];
            }
          });
        }
      } else {}
    }).catchError((e) {
      print(e.toString());
    });
  }

  _warninghCallBack(int id) {
    var map = {
      "id": id,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.policyWarningCalled, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          _onRefresh();
        }
      } else {}
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
    });
  }

  _fectData() {
    var map = {
      'page': _page,
      'rows': 20,
      'status': cellType,
    };

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.policyWarningList}', data: map)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            PolicyWarningEntity model =
                PolicyWarningEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              _controller.finishLoad(
                  success: true, noMore: (model.rows??[]).length != 20);
              setState(() {
                if (_page == 1) {
                  /// 刷新
                  dataList.clear();
                  chooseList.clear();
                  dataList.addAll(model.rows??[]);

                } else {
                  dataList.addAll(model.rows??[]);
                }
              });
            } else {
              if (_page == 1) {
                // 刷新
                setState(() {
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                });
              }
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _onRefresh() async {
    _page = 1;
    await _fectTopItemCount();
    await _fectData();
  }

  Future _loadMore() async {
    _page++;
    await _fectData();
  }


  Future<void> batchSubmit() async {
    if(chooseList.isEmpty){
      Toast.show("请选择批量执行的项目");
      return;
    }
    var page = SVProgressHUD(context);
    page.showProgress(hint: "提交中...");
      try{
        var map = {
          "callInfoIds":chooseList.map((e)=>e.id).toList(),
        };
        var url = "${HttpApi.baseUrl}callInfo/batchDealCallInfo";
        var data = await HttpGo.instance.postData(url,data: map,options: Options(contentType: Headers.jsonContentType));
        if("0"==data['code']){
          page.closeProgress();
          setState(() {
            chooseList.clear();
            inBatchMode = false;
          });
          _onRefresh();
        }else{
          Toast.show(data['msg']);
        }
      }catch(e){
        Toast.show(NetErrorUtils.getNetError(e));
        page.closeProgress();

    }

  }
}
